﻿using System;
using System.IO;
using System.Web;
using System.Configuration;

namespace Shuba.Web.bulk_upload
{
    public partial class topup_upload_bulk : basePage
    {
        string msg = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_TOPUP");
                if (!IsUserAdd(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }
                LabelTitle.Text = String.Format("Bulk Upload {0}", GetPageTitle("MSTR_TOPUP"));
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                lblStatus.Text = "";
                status.Visible = false;
            }
            if (IsPostBack)
            {
                Boolean fileOK = false;
                string path = Server.MapPath("~/uploads/");
                string ErrMessage = "";

                if (FileUpload1.HasFile)
                {
                    int fileSize = FileUpload1.PostedFile.ContentLength / 1024;
                    int maxupload = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["max.upload"]);
                    
                    String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();

                    if (fileSize <= maxupload && fileExtension == ".zip") fileOK = true;

                    if (fileSize > maxupload)
                    {
                        Alert("Ukuran File leih besar daripada yang diperbolehkan");
                        fileOK = false;
                        FileUpLoadValidator.Visible = false;
                        return;
                    }
                    //if (!fileOK) FileUpLoadValidator.ErrorMessage = "Upload zip with tab delimited only and maximum file upload " + maxupload.ToString() + " KB";

                    //if (!FileUpload1.FileName.ToLower().Trim().Substring(0, 5).Contains("topup")) fileOK = false;
                }

                if (fileOK)
                {
                    try
                    {
                        bool OK = true;
                        status.Visible = true;

                        Shuba.Business.BulkUp bulk = new Shuba.Business.BulkUp();

                        string fNameZip = path + Session["UserID"].ToString() + FileUpload1.FileName;
                        FileUpload1.PostedFile.SaveAs(fNameZip);

                        string fileNameZip = DecompressZip(fNameZip);
                        string fn = fileNameZip.Substring(0, 6);
                        if (fn == "FAILED")
                        {
                            Alert("Jumlah File Pada Zip Lebih Dari 1 File\\nJumlah File = " + fileNameZip.Substring(6));
                            OK = false;
                            FileUpLoadValidator.Visible = false;
                            return;
                        }

                        if (fileNameZip == "CORRUPT")
                        {
                            Alert("File Zip Corrupt\\nSilahkan upload ulang dengan file zip yang valid");
                            OK = false;
                            FileUpLoadValidator.Visible = false;
                            return;
                        }
                        else
                        {
                            string[] ext = fileNameZip.Split('.');
                            if (ext.Length > 2) //jika file name terdapat titik
                            {
                                Alert("Filename tidak Boleh terdapat .(titik)\\nSilahkan ubah nama file dan upload ulang dengan file zip yang valid");
                                OK = false;
                                FileUpLoadValidator.Visible = false;
                                return;
                            }
                            if (ext[1].ToLower() != "txt")
                            {
                                Alert("File Zip Bukan Berisi File .txt\\nSilahkan upload ulang dengan file zip yang valid");
                                OK = false;
                                FileUpLoadValidator.Visible = false;
                                return;
                            }
                        }

                        if (fn != "FAILED" && OK)
                        {
                            string fName = path + fileNameZip;

                            var filestream = File.OpenText(fName);
                            string contains = filestream.ReadToEnd();
                            filestream.Close();

                            char rowDelimiter = '\n';
                            char fldDelimiter = '\t';

                            var rows = contains.Split(rowDelimiter);
                            var rowscount = rows[2].Split(fldDelimiter);
                            int jumlah = 0;

                            for (var i = 0; i < rows.Length; i++)
                            {
                                string baris = rows[i].Trim();
                                if (!baris.Equals("F") || !baris.Equals("\r") || !baris.Equals(""))
                                {
                                    if (!baris.Equals("F") && baris.Length > 0)
                                    {
                                        jumlah = i + 1;
                                    }
                                }
                                if (baris.Equals("F"))
                                {
                                    break;
                                }
                            }

                            if (OK && (rows[0].Split('\t')[1].Trim() != fileNameZip.Split('.')[0]))
                            {
                                Alert("Nama file berbeda dengan nama batch\\nSilakan cek dan ubah batch id pada text file upload");
                                OK = false;
                            }

                            //bool isSpace = System.Text.RegularExpressions.Regex.IsMatch(rows[0].Split('\t')[1].Trim(), "^[\\s]+$");
                            if (OK && rows[0].Split('\t')[1].Trim().Contains(" "))
                            {
                                Alert("Format Batch ID salah\\nSilakan cek dan ubah batch id pada text file upload");
                                OK = false;
                            }

                            if (OK && rows[0].Split('\t')[1].Trim().Length > 20)
                            {
                                Alert("Panjang Karakter Batch ID Salah\\nSilakan cek dan ubah panjang karakter batch id pada text file upload");
                                OK = false;
                                return;
                            }

                            if (OK && (bulk.Get(fileNameZip.Split('.')[0]).BATCH_ID != null))
                            {
                                Alert("Batch ini telah terupload sebelumnya\\nSilakan cek dan ubah batch id pada text file upload");
                                OK = false;
                            }

                            string currDate = ProcessingDate().ToString("MM-dd-yyyy");
                            DateTime textDate = Convert.ToDateTime(rows[1].Split('\t')[1].Trim());
                            string DateText = textDate.ToString("MM-dd-yyyy");
                            if (!currDate.Equals(DateText)) //rows[1].Split('\t')[1].Trim().Replace('\\', '-')
                            {
                                Alert("Header Tanggal tidak sesuai dengan tanggal sekarang\\nSilakan cek dan ubah header tanggal pada text file upload");
                                OK = false;
                                FileUpLoadValidator.Visible = false;
                                return;
                            }

                            try
                            {
                                Convert.ToInt32(rowscount[1].Trim());
                            }
                            catch (Exception excep)
                            {
                                Alert("Format Rowcount tidak sesuai format\\nSilakan cek dan ubah jumlah format row header pada text file upload");
                                OK = false;
                                return;
                            }

                            if (rowscount[1].Trim() != (jumlah - 4).ToString()) //rowscount[1].Trim() != (rows.Length - 6).ToString() 
                            {
                                Alert("Jumlah row header berbeda dengan jumlah row sebenarnya\\nSilakan cek dan ubah jumlah row header pada text file upload");
                                OK = false;
                                return;
                            }

                            if (rows[jumlah].Contains("\t"))
                            {
                                string[] foot = rows[jumlah].Split('\t');
                                if (!foot[0].Equals("F"))
                                {
                                    Alert("Text file tidak terdapat footer\\nSilakan cek dan ubah jumlah pada text file upload");
                                    OK = false;
                                    FileUpLoadValidator.Visible = false;
                                    return;
                                }
                            }
                            else if (!rows[jumlah].Contains("\t") && !rows[jumlah].Trim().Equals("F"))
                            {
                                Alert("Text file tidak terdapat footer\\nSilakan cek dan ubah jumlah pada text file upload");
                                OK = false;
                                FileUpLoadValidator.Visible = false;
                                return;
                            }

                            if (OK)
                            {
                                try
                                {
                                    string appPath = Server.MapPath("~/console/BulkUp.exe");

                                    bulk.ExecuteCommand(appPath, fName, "topup", HttpContext.Current.User.Identity.Name);

                                    AddLog("UPLOAD", "UPLOAD TOPUP");
                                    FileUpLoadValidator.Visible = false;
                                    AlertAndRedirect("File Successfully Uploaded", "topup_monitoring.aspx");
                                }
                                catch (Exception ex)
                                {
                                    ErrMessage += this.GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                                    ErrMessage += "<br>" + ex.Message + "<br><br>Please check your data";
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrMessage += this.GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                        ErrMessage += "<br>" + ex.Message + "<br><br>Please check your data";
                    }
                }
            }
        }

        private string DecompressZip(string PathSaveFile)
        {
            string fileName = "";
            string path = Server.MapPath("~/uploads/");
            try
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipInputStream s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(PathSaveFile)))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry;
                    int jmlFile = 0;

                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        jmlFile++;
                        using (FileStream streamWriter = File.Create(String.Format("{0}\\{1}", path, theEntry.Name)))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];

                            while (true)
                            {
                                try
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }
                            streamWriter.Close();
                            fileName = theEntry.Name;
                        }
                    }
                    if (jmlFile > 1)
                    {
                        return "FAILED" + jmlFile.ToString();
                    }
                }
            }
            catch (Exception e)
            {
                if (e.Message == "Wrong Local header signature: 0xE011CFD0") { return "CORRUPT"; }
            }
            
            return fileName;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("topup_monitoring.aspx");
        }
    }
}